package com.test.task;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.id.UUIDHexGenerator;

import com.test.dao.HibernateUtil;
import com.test.model.Student;
import com.test.util.DateUtil;
import com.test.util.TaskUtil;



public class AddStudentTask implements Task{
	
	/**
	 *休眠时间 
	 */
	private static final int SLEEP_TIME = 60000;//3600000;
	
	public void run() {
		// TODO Auto-generated method stub
		execute();
	}
	
	public void execute(){
		synchronized(TaskUtil.addStudentTaskCount){
			TaskUtil.addStudentTaskCount++;
		}
		System.out.println(getTaskName()+"任务开始");
		Long beginTime = System.currentTimeMillis();  
        double num = Math.random()*100;
        //进行50000条插入
        if(num%2<1){
        	System.out.println(getTaskName()+"本次插入数量50000");
        	double _num =Math.random()*10;
        	if(_num%2<1){
        		System.out.println(getTaskName()+"使用hibernate进行批量插入");
        		//使用hiberante进行大批量插入
        		Session session = HibernateUtil.getSessionFactory().openSession();
        		Transaction tx = session.beginTransaction();
        		for(int i=0;i<50000;i++){
        			String nowDate = DateUtil.getCurrentTime();
        			Student _stu = new Student();
        			_stu.setClassId(""+(i/10000+1));
        			_stu.setGradeId("1");
        			_stu.setSname("小"+i+"同学");
        			_stu.setCreateTime(nowDate);
        			_stu.setStudentId("stu"+i);
        			_stu.setStatus((i%2!=1)?"1":"0");
        			_stu.setDataFrom("HIBERNATE");
        			session.save(_stu);
        			if(i%100==0){
        				session.flush(); 
        				session.clear(); 
        			}
        		}
        		tx.commit(); 
        		
        		if(session!=null && session.isOpen())
        			session.close(); 
        	}else{
        		System.out.println(getTaskName()+"使用jdbc进行批量插入");
        		//使用jdbc进行大批量插入
        		Connection conn = HibernateUtil.getSessionFactory().openSession().connection();
        		try{
        			conn.setAutoCommit(false);//设置手动提交 
            		String sql=" insert into student (id,sname,studentId,classId,gradeId,createTime,status,dataFrom)" +  
                    " values (?,?,?,?,?,?,?,?) ";  
            		PreparedStatement pst=conn.prepareStatement(sql);  
    				for(int i=0;i<50000;i++){
    					String nowDate = DateUtil.getCurrentTime();
    					//主键生成
    					UUIDHexGenerator uuidGenerator=new UUIDHexGenerator();
    					pst.setString(1,uuidGenerator.generate(null, null).toString());
    					pst.setString(2, "小"+i+"同学");
    					pst.setString(3, "stu"+i);
    					pst.setString(4, ""+(i/10000+1));
    					pst.setString(5, "1");
    					pst.setString(6, nowDate);
    					pst.setString(7, (i%2!=1)?"1":"0");
    					pst.setString(8,"JDBC");
    					pst.execute(); 
    	            }
    				conn.commit();
    				closeJdbcConn(conn,pst,null);
        		}catch(SQLException ex){
        			ex.printStackTrace();
        		}
        		
        	}
        	String nowDate = DateUtil.getCurrentTime();
        }else{
        	System.out.println(getTaskName()+"本次插入数量6666");
    		Session session = HibernateUtil.getSessionFactory().openSession();
    		Transaction tx = session.beginTransaction();
    		for(int i=0;i<6666;i++){
    			String nowDate = DateUtil.getCurrentTime();
    			Student _stu = new Student();
    			_stu.setClassId(""+(i/10000+1));
    			_stu.setGradeId("1");
    			_stu.setSname("小"+i+"同学");
    			_stu.setCreateTime(nowDate);
    			_stu.setStudentId("stu"+i);
    			_stu.setStatus((i%2!=1)?"1":"0");
    			_stu.setDataFrom("COMMON");
    			session.save(_stu);
    			if(i%100==0){
    				session.flush(); 
    				session.clear(); 
    			}
    		}
    		tx.commit(); 
    		if(session!=null && session.isOpen())
    			session.close(); 
        }
        
        Long endTime = System.currentTimeMillis(); 
        System.out.println(getTaskName()+"本次增加学生任务结束：耗时"+(endTime-beginTime)+"毫秒/"+(endTime-beginTime)/1000+"秒");//计算时间   
		System.out.println(getTaskName()+"线程开始休眠,休眠时间:"+(SLEEP_TIME/1000)+"秒");
		try {
			Thread.sleep(SLEEP_TIME);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		execute();
	}

	public String getTaskName() {
		return "第"+TaskUtil.addStudentTaskCount+"轮：Task[AddUserTask]";
	}
	
	public void closeJdbcConn(Connection conn,Statement s, ResultSet rs) throws SQLException{
		if(rs!=null)
			rs.close();
		if(s!=null)
			s.close();
		if(conn!=null)
			conn.close();
	}
}
